using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Main : MonoBehaviour 
{
	
	private enum Mode
	{
		Line, //Draws Line Segments at points
		BezierInterpolated, //Interpolates 
	}
	
	private Mode mode;
	private List<Vector3> points;
    private List<Vector3> gizmos;	
	private LineRenderer lineRenderer;

	// Use this for initialization
	void Start () 
	{
		lineRenderer = GetComponent<LineRenderer>();
		points = new List<Vector3>();
		
		mode = Mode.BezierInterpolated;
	}
	
	// Update is called once per frame
	void Update () 
	{
		ProcessInput();
		Render();
	}
	
	private void ProcessInput()
	{
    	if (Input.GetMouseButtonDown(0))
	    {
	        Vector2 screenPosition = Input.mousePosition;
	        Vector3 worldPosition = Camera.main.ScreenToWorldPoint(new Vector3(screenPosition.x, screenPosition.y, 4));

	        points.Add(worldPosition);
	    }

        if (Input.GetKeyDown(KeyCode.X))
        {
            points.Clear();
        }
	}
	
	private void Render()
	{
		switch(mode)
		{
			case Mode.Line:
				RenderLineSegments();
			break;
            case Mode.BezierInterpolated:
                BezierInterpolate();
            break;
		}
	}
	
	private void RenderLineSegments()
	{
        gizmos = points;
        SetLinePoints(points);
	}

    private void BezierInterpolate()
    {
        BezierPath bezierPath = new BezierPath();
        bezierPath.Interpolate(EditorCamera.keyList, .25f);

		List<Vector3> drawingPoints = bezierPath.GetDrawingPoints0();
        
        gizmos = bezierPath.GetControlPoints();  

        SetLinePoints(drawingPoints);
    }

    private void SetLinePoints(List<Vector3> drawingPoints)
    {
        lineRenderer.SetVertexCount(drawingPoints.Count);

        for (int i = 0; i < drawingPoints.Count; i++)
        {
            lineRenderer.SetPosition(i, drawingPoints[i]);
        }
    }

    public void OnDrawGizmos()
    {
        if (gizmos == null)
        {
            return;
        }        

        for (int i = 0; i < gizmos.Count; i++)
        {
            Gizmos.DrawWireSphere(gizmos[i], 1f);            
        }
    }

    public void OnGUI()
    {
        GUILayout.BeginArea(new Rect(10, 50, 300, 300));
//        GUILayout.Label("F1 Line Segments (Click to add points)");
//        GUILayout.Label("F2 Bezier interpolation (Click to add points)");
        GUILayout.Label("X  Clear");
        GUILayout.EndArea();
    }
}
